package com.linchong.concurrency.chapter7;

/**
 * @Author:linchong
 * @CreateTime:2020-01-07 08:49
 * @Description:测试this锁
 */
public class SynchronizedThis {

	public static void main(String[] args) {
		ThisLock thisLock = new ThisLock();
		new Thread("T1") {
			@Override
			public void run() {
				thisLock.m1();
			}
		}.start();

		new Thread("T2") {
			@Override
			public void run() {
				thisLock.m2();
			}
		}.start();
	}
}

class ThisLock {
	private final Object LOCK = new Object();

	public synchronized void m1() {
		System.out.println(Thread.currentThread().getName());
		try {
			Thread.sleep(10_000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	/**
	 * v1.0
	 * public void m2(){*/
	/**
	 * this锁，m1方法和m2方法锁住的是同一把this锁
	 * */
	/**
	 * v2.0
	 * public synchronized void m2(){
	 */
	public void m2() {
		//v3.0
		synchronized (LOCK) {
			try {
				System.out.println(Thread.currentThread().getName());
				Thread.sleep(10_000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}